<template>
  <div>
    <div>
      <Card :bordered="false" class="classWp">
        <p slot="title">类别管理</p>
        <Input
          search
          enter-button="+"
          placeholder="请输入类别"
          size="small"
          v-model.trim="typeStr"
          @keyup.enter="addType"
          @on-search="addType"
        />
        <br />
        <Tag
          v-for="(item,index) in typeArr"
          :key="index"
          :name="item.id"
          closable
          checkable
          @on-change="changeType"
          color="primary"
          @on-close="removeType"
        >{{ item.name }}</Tag>
      </Card>
    </div>
  </div>
</template>

<script>
import { BdTypeUrl } from "../baseUrl/index";
import axios from "../axios";
export default {
  data() {
    return {
      typeArr: [],
      typeStr: "",
      changeId: ""
    };
  },
  methods: {
    addType() {
      if (!this.typeStr) {
          return
      }
        let url = BdTypeUrl,
          method = "post";
        if (this.changeId) {
          url = `${BdTypeUrl}/${this.changeId}`;
          method = "put";
        }
        axios({
          url,
          method,
          data: {
            name: this.typeStr
          },
          success: data => {
            this.typeStr = "";
            this.getType();
          }
        });
    },
    changeType(checked, name) {
      if (!checked) {
        this.changeId = name;
      } else {
        this.changeId = "";
      }
    },
    removeType(event, name) {
      if (confirm("确定要删除该类别吗")) {
        axios({
          url: `${BdTypeUrl}/${name}`,
          method: "delete",
          success: data => {
            this.getType();
          }
        });
      }
    },
    getType() {
      axios({
        url: BdTypeUrl,
        method: "get",
        params: {
          transform: 1
        },
        success: data => {
          this.typeArr = data.data.bdtype;
        }
      });
    }
  },
  mounted() {
    this.getType();
  }
};
</script>

<style>
.classWp {
  border: 1px solid #ccc;
  border-radius: 5px;
  min-width: 300px;
  max-width: 30%;
  height: 325px;
  margin: 20px;
}
</style>
